<template>
  <div class="surveys">
    <div class="header">
      <h2>问卷列表</h2>
      <el-button type="primary" @click="$router.push('/create')">
        <el-icon>
          <Plus />
        </el-icon>创建问卷
      </el-button>
    </div>

    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm">
        <el-form-item label="问卷标题">
          <el-input v-model="filterForm.title" placeholder="请输入问卷标题" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filterForm.status" placeholder="请选择状态">
            <el-option label="全部" value="" />
            <el-option label="进行中" value="active" />
            <el-option label="已结束" value="ended" />
            <el-option label="草稿" value="draft" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-table :data="surveys" style="width: 100%" class="mt-20" :loading="loading" empty-text="没有找到符合条件的问卷">
      <el-table-column prop="id" label="问卷编号" width="180" />
      <el-table-column prop="title" label="问卷标题" />
      <el-table-column prop="created_at" label="创建时间" />
      <el-table-column prop="end_time" label="结束时间" />
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="responses" label="填写人数" /> -->
      <el-table-column label="操作" width="250">
        <template #default="scope">
          <el-button-group>
            <el-button type="primary" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button type="warning" @click="share(scope.row)" style="margin-left: 5px;">
              分享
            </el-button>
            <el-button type="danger" @click="handleDelete(scope.row)" style="margin-left: 5px;">
              删除
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination v-model:current-page="page" v-model:page-size="size" :page-sizes="[5, 10, 15, 20]"
        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Plus, CopyDocument } from '@element-plus/icons-vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'

// 配置Axios请求
const instance = axios.create({
  baseURL: 'http://localhost:3000',
  timeout: 5000
})

const router = useRouter()
// 响应式数据
const filterForm = reactive({
  title: '',
  status: ''
})
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const surveys = ref([])
const loading = ref(false)

// 初始加载数据
onMounted(() => {
  handleSearch()
})


const handleSearch = async () => {
  loading.value = true
  try {
    const res = await instance.get('/api/surveys', {
      params: {
        title: filterForm.title,
        status: filterForm.status,
        page: currentPage.value,
        pageSize: pageSize.value
      }
    })
    surveys.value = res.data.data.list
    total.value = res.data.data.total
  } catch (error) {
    console.error('请求失败:', error)
    ElMessage.error('获取数据失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

const resetFilter = () => {
  filterForm.title = ''
  filterForm.status = ''
  handleSearch()
}

const getStatusType = (status) => {
  const types = {
    active: 'success',
    ended: 'info',
    draft: 'warning'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    active: '进行中',
    ended: '已结束',
    draft: '草稿'
  }
  return texts[status] || status
}

const handleSizeChange = (size) => {
  currentPage.value = 1 // 搜索时重置到第一页
  pageSize.value = size
  handleSearch()
}

const handleCurrentChange = (page) => {
  currentPage.value = page;
  handleSearch()
}

// 待实现的操作方法（示例）
const handleEdit = (row) => {
  router.push(`/edit/${row.id}`)
}

// 分享问卷
const share = (row) => {
  // 检查问卷状态，只有进行中的问卷才能分享
  if (row.status !== 'active') {
    ElMessage.warning('只有进行中的问卷才能分享')
    return
  }
  
  // 生成分享链接
  const shareLink = `${window.location.origin}/answer/${row.id}`
  
  // 显示分享对话框
  ElMessageBox.alert(
    `分享链接：<span style="color: #409EFF; word-break: break-all;">${shareLink}</span>`,
    '分享问卷',
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '关闭',
      showCancelButton: true,
      cancelButtonText: '复制链接',
      cancelButtonClass: 'el-button--primary',
      callback: (action) => {
        if (action === 'cancel') {
          copyShareLink(shareLink)
        }
      }
    }
  )
}

// 复制分享链接
const copyShareLink = (link) => {
  navigator.clipboard.writeText(link).then(() => {
    ElMessage.success('链接已复制到剪贴板')
  }).catch(() => {
    ElMessage.error('复制失败，请手动复制')
  })
}

//删除问卷
async function handleDelete(row) {
  try {
    const confirmResult = await ElMessageBox.confirm(
      '确定要删除这份问卷吗？此操作不可恢复',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    if (confirmResult === 'confirm') {
      const res = await instance.delete(`/api/surveys/${row.id}`)
      if (res.data.code === 200) {
        ElMessage.success('删除成功')
        // 如果当前页只有一条数据且不是第一页，则跳转到上一页
        if (surveys.value.length === 1 && currentPage.value > 1) {
          currentPage.value--
        }
        handleSearch()
      } else {
        throw new Error(res.data.message || '删除失败')
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除操作失败，请稍后重试')
    }
  }
}
</script>

<style scoped>
.surveys {
  padding: 20px;
  height: 100%;
  box-sizing: border-box;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  color: #67C23A;
  margin: 0;
}

.filter-card {
  margin-bottom: 20px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.mt-20 {
  margin-top: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-button--primary) {
  background-color: #67C23A;
  border-color: #67C23A;
}

:deep(.el-button--primary:hover) {
  background-color: #85ce61;
  border-color: #85ce61;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #67C23A;
  font-weight: bold;
}

/* 分享链接样式 */
.share-link-container {
  text-align: center;
}

.share-link-box {
  display: flex;
  margin: 15px 0;
}

.share-input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
}

.share-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 10px;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-tag--success) {
  background-color: #f0f9eb;
  border-color: #e1f3d8;
  color: #67C23A;
}

:deep(.el-tag--info) {
  background-color: #f4f4f5;
  border-color: #e9e9eb;
  color: #909399;
}

:deep(.el-tag--warning) {
  background-color: #fdf6ec;
  border-color: #faecd8;
  color: #e6a23c;
}

/* 分享链接样式 */
:deep(.share-link-container) {
  text-align: center;
}

:deep(.share-link-box) {
  display: flex;
  margin: 15px 0;
}

:deep(.share-input) {
  margin-right: 10px;
}

:deep(.share-tip) {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
}

:deep(.el-message-box__message p) {
  margin: 0;
  line-height: 1.5;
}
</style>